<?php

namespace App\Models\Factory\V0;



use App\Helpers\Bank;
use App\Models\AbsModelFactory;
use App\Models\Orm\V0\Bankbin;
use App\Models\Orm\V0\BankbinName;
use App\Models\Orm\V0\Bankbinnew;
use App\Models\Orm\V0\UserCredit;
use App\Services\Core\Store\Hengxin\HengxinConfig;


/**
 * 生成恒信订单号
 */
class BankFactory extends AbsModelFactory
{
    /**
     * 通过卡bin拿到开户行行号
     *
     * @param int $action_code
     * @return bool|string
     */
    public static function fetchBank($accNo)
    {
        //首先截取银行卡前6位
        $nums = [6, 8, 9, 7,5, 4, 3,10];
        foreach ($nums as $num) {
            $substr1 = substr($accNo, 0, $num);
            $result = Bankbinnew::where('bank_code', $substr1)->first();
            if ($result) {
                return $result;
                break;
            }
        }

        return false;
    }



    public static function fetchBankBin($accNo)
    {
        //首先截取银行卡前6位
        $nums = [6, 8, 9, 7,5, 4, 3,10];
        foreach ($nums as $num) {
            $substr1 = substr($accNo, 0, $num);
            $result = Bankbin::where('card_id', $substr1)->first();
            if ($result) {
                return $result;
                break;
            }
        }

        return false;
    }


    /**
     * 通过卡bin拿到银行名
     *
     * @param int $action_code
     * @return bool|string
     */
    public static function fetchBankNanme($accNo)
    {
        //首先截取银行卡前6位
        $nums = [6, 8, 9, 7, 5, 3,10];
        foreach ($nums as $num) {
            $substr1 = substr($accNo, 0, $num);
            $result = BankbinName::where('bank_code', $substr1)->first();
            if ($result) {
                return $result;
                break;
            }
        }

        return false;
    }


    //银行卡中间加***
    public  static  function formatBankCardNo($bankCardNo)
    {
        //截取银行卡号前4位
//        $prefix = substr($bankCardNo,0,4);
        //截取银行卡号后4位
        $suffix = substr($bankCardNo,-4,4);

        $maskBankCardNo = " **** **** **** ".$suffix;


        return $maskBankCardNo;
    }





    //通过token和卡号拿到用户的token
    public static function getToken($accNo, $user_id)
    {
        $result = UserCredit::where('user_id', $user_id)->where('credit_card', $accNo)->where('is_open',1)->first();
        return $result ? $result : false;
    }

    //插入银行token
    public static function addCredit($orderId, $data)
    {

        //如果发现之前有人绑定过直接解除绑定清零
        $creditObj = UserCredit::where('orderId', $orderId)->first();
        if(substr($creditObj->credit_card,-4) != $data['credit_card'])
        {
            return false;
        }

        $creditObj->bank_token = $data['token'];
        $creditObj->token_level = $data['tokenLevel'];
        $creditObj->token_begin = $data['tokenBegin'];
        $creditObj->token_end = $data['tokenEnd'];
        $creditObj->token_type = $data['tokenType'];
        $creditObj->is_open = 1;
        $creditObj->is_query = 2;

//        dd($creditObj->save());
        if ($creditObj->save()) {
            return $creditObj->user_id;
        };

        return false;
    }

    //开通失败把开通状态传到数据库
    public static  function addCredits($orderId,$data)
    {
        $creditObj = UserCredit::where('orderId', $orderId)->first();
        if(substr($creditObj->credit_card,-4) != $data['credit_card'])
        {
            return false;
        }
        $creditObj->is_open = 2;
        $creditObj->is_query = 2;


        if ($creditObj->save()) {
            return $creditObj->user_id;
        };

        return false;
    }


    //插入信用卡
    public static function addCreditByUser($user_id, $data)
    {


        $data['user_id'] = $user_id;
        $data['is_open'] = 0;
        $data['is_query'] = 0;
        $data['bank_token'] = 0;
        $result = UserCredit::updateOrCreate(['user_id' => $user_id,'credit_card'=>$data['credit_card']], $data);
        return $result ? $result : false;
    }

    //直接跳转银联更新订单号和订单时间
    public static  function updateOrderId($user_id,$credit_card_id,$data)
    {
        $data['is_open'] = 0;
        $data['is_query'] = 0;
        $data['bank_token'] = 0;
        $result = UserCredit::where('id',$credit_card_id)->where('user_id',$user_id)->update($data);
        return $result ? $result : false;
    }




    //计算出无积分代付金额
    public static function gettxnAmtDF($txnAmtTrans)
    {
        $txnAmtDF = $txnAmtTrans - ($txnAmtTrans * (HengxinConfig::moneyRateNull)) - HengxinConfig::ServiceChargeNull;
        if (is_float($txnAmtDF)) {
            $txnAmtDF = ceil($txnAmtDF);
        }
        return $txnAmtDF;
    }
    //计算出有积分代付金额    }

    public static function gettxnAmtDFFont($txnAmtTrans)
    {
        $txnAmtDF = $txnAmtTrans - ($txnAmtTrans * (HengxinConfig::moneyRate)) - HengxinConfig::ServiceCharge;
        if(is_float($txnAmtDF)){
            $txnAmtDF = ceil($txnAmtDF);
        }
        return $txnAmtDF;
    }


    public static function getUserByPhoneNO($phoneNo)
    {
        $result = UserCredit::where('phoneNo',$phoneNo)->first();
        return $result ? true :false;
    }

    //获取用户的信用卡号
    public static  function getCreditCard($user_id)
    {
        $result = UserCredit::where('user_id',$user_id)->get(array('id','credit_card','bankNameTrans','bank_logo','bank_token'))->toArray();
        return $result ? $result : '';
    }


    //通过银行卡id和用户id拿到银行卡
    public static  function getUserCredit($user_id,$id)
    {
        $credit_card = UserCredit::where('user_id',$user_id)->where('id',$id)->first();
        return $credit_card ? $credit_card : '';
    }


    //识别银行卡
    public static  function fetchBankCard($bankBase64)
    {

        $host = "https://yhk.market.alicloudapi.com";
        $path = "/rest/160601/ocr/ocr_bank_card.json";
        $method = "POST";
        $appcode = "652e57e76e014140a1fc93e0b1e6e6f9";
        $headers = array();
        array_push($headers, "Authorization:APPCODE " . $appcode);
        //根据API的要求，定义相对应的Content-Type
        array_push($headers, "Content-Type".":"."application/json; charset=UTF-8");
        $querys = "";
//        $bodys = "{\"inputs\":[{\"image\":{\"dataType\":50,#50表示image的数据类型为字符串\"dataValue\":\"base64_image_string\"#图片以base64编码的string}}]}";
        $bodys = '{
                "inputs": [
                {
                    "image": {
                        "dataType": 50,                         
                        "dataValue": '.'"'.''.$bankBase64.'"'.'     
                    }
                }]
}';
//        dd($bodys);
        $url = $host . $path;

        $curl = curl_init();
        curl_setopt($curl, CURLOPT_CUSTOMREQUEST, $method);
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
        curl_setopt($curl, CURLOPT_FAILONERROR, false);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($curl, CURLOPT_HEADER, true);
        if (1 == strpos("$".$host, "https://"))
        {
            curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
            curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
        }
        curl_setopt($curl, CURLOPT_POSTFIELDS, $bodys);
        $result = curl_exec($curl);
        if(strpos($result,'outputs') == true) {

            $Card = strstr($result, 'includeSubDomains;');
            $length = strlen('includeSubDomains;');
            $Card = substr($Card, $length);
            $Card = \GuzzleHttp\json_decode($Card, true);
            //$idCard['outputs'][0]['outputValue']['dataValue']身份证信息
            $idcardDetail = \GuzzleHttp\json_decode($Card['outputs'][0]['outputValue']['dataValue'], true);
           if(array_key_exists('err_msg',$idcardDetail)){
               return false;
           };
               $card_num['card_num'] = $idcardDetail['card_num'];//银行卡号
               return $card_num;

        }
        return false;

    }

    //删除银行卡
    public static function delBankCard($user_id,$id)
    {
        $result = UserCredit::where('user_id',$user_id)->where('id',$id)->delete();
        return $result ? true : false;
    }

    public static  function fetchBankLogo($bankNameTrans)
    {
        //银行logo的数组
        $bank_logos = config('anwen.bank_logo');
        if(array_key_exists($bankNameTrans,$bank_logos))
        {
            return  $bank_logos[$bankNameTrans];
        }else{

            return  $bank_logos['默认信用卡'];
        }
    }

    //拿到用户信用卡
    public static function getCredit($user_id){

        $result = UserCredit::select('id','bankNameTrans','bank_logo','bank_token','phoneNo','credit_card')->where('user_id',$user_id)->get()->toArray();
        return empty($result) ?  false: $result;
    }

    //拿到用户信用卡
    public static function getCreditByOrderId($orderId){

        $result = UserCredit::where('orderId',$orderId)->first()->toArray();
        return $result ?  $result : false;
    }
}